package com.jetinno.simple.utils

import android.text.TextUtils
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import java.lang.reflect.Type

/**
 * Created by zhangyuncai on 2019/6/28.OK
 * json字符串解析
 */
object JsonUtil {
    private val gson = Gson()

    /**
     * 把对象转成json字符串
     * exp:
     * val list = mutableListOf<Student>()
    list.add(Student("xiaoming",10))
    list.add(Student("xiaoming",10))
    list.add(Student("xiaoming",10))
    list.add(Student("xiaoming",10))
    val json = JsonUtil.anyToJson(list)
     */
    fun anyToJson(src: Any?): String {
        var jsonStr = ""
        try {
            if (src == null) {
                return jsonStr
            }
            jsonStr = gson.toJson(src)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return jsonStr
    }

    ///会输出空字段
    fun anyToJsonHasNull(src: Any?): String {
        val gsonBuilder = GsonBuilder()
        val gson = gsonBuilder.serializeNulls().create()
        var jsonStr = ""
        try {
            if (src == null) {
                return jsonStr
            }
            jsonStr = gson.toJson(src)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return jsonStr
    }

    /**
     *解析json字符串,返回对象
     */
    fun <T> jsonToAny(src: String?, clazz: Class<T>): T? {
        try {
            if (TextUtils.isEmpty(src)) {
                return null
            }
            val t = gson.fromJson(src, clazz)
            return t
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }

    /**
     *解析json字符串,返回对象
     * exp:
     * val type = object : TypeToken<MutableList<Student>>() {}.type
    val fromJson = Gson().fromJson<MutableList<Student>>(json, type)
     */
    fun <T> jsonToAny(src: String?, type: Type): T? {
        try {
            if (TextUtils.isEmpty(src)) {
                return null
            }
            val t = gson.fromJson<T>(src, type)
            return t
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }



}